package ms.platform.util;



import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


public class AESUtil {
	private static final String AES_MODEL = "AES/CBC/NoPadding";
    private static final String AES = "AES";

    /**
     * 方法描述：加密方法
     * @param: 
     * @return: 
     * @version: 1.0
     * @author: cheng shen
     * @version: 2017年10月17日 下午3:25:12
     */
    public static String encrypt(String raw, String key, String iv) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(AES_MODEL);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = raw.getBytes();
            int dataLenth = dataBytes.length;
            if (dataLenth % blockSize != 0) {
                dataLenth = dataLenth + (blockSize - (dataLenth % blockSize));
            }
            byte[] plaintext = new byte[dataLenth];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), AES);
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String data, String key, String iv) throws Exception {
        try {
            byte[] encrypted1 = Base64.decodeBase64(data);
            Cipher cipher = Cipher.getInstance(AES_MODEL);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), AES);
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
   

}
